package library;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

//Class to add url query
public class QueryString {

  private String query = "";

  public QueryString(String name, String value) {
    encode(name, value);
  }

  public void add(String name, String value) {
    query += "&";
    encode(name, value);
  }

  private void encode(String name, String value) {
    try {
      query += URLEncoder.encode(name, "UTF-8");
      query += "=";
      query += URLEncoder.encode(value, "UTF-8");
    } catch (UnsupportedEncodingException ex) {
      throw new RuntimeException("Broken VM does not support UTF-8");
    }
  }

  public String getQuery() {
    return query;
  }

  @Override
  public String toString() {
    return query;
  }

  public static void main(String[] args) {
    QueryString qs = new QueryString("pg", "q");
    qs.add("kl", "XX");
    qs.add("stype", "stext");
    qs.add("q", "+\"Java Programming\"");
    String url = "http://www.java.com/query?" + qs;
    try {
      System.out.println(URLDecoder.decode(url, "UTF-8"));
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  
}
